import React, {useEffect, useState} from "react";
import {Button, Divider, Space, Table} from "antd";
import _ from "lodash";
import {SyncOutlined} from "@ant-design/icons";
import FuncBtnGroup from "@/components/FuncBtnGroup";
import Moment from "moment";
import {FuncGroupsProps} from "@/components/FuncBtnGroup/constants";
import A from "@/components/A";
import {IPageResponse, PageInfo} from "@/common/common";
import {useHistory} from "react-router-dom";
import {ColumnsType} from "antd/lib/table";

interface IProps {
  pageResponse?: IPageResponse<any>
  delRecord: (id: number[]) => any
  handleRecord: (id: number[]) => any
  onChangePage: (page: PageInfo) => any
}

const AlarmList = (props: IProps) => {

  const history = useHistory()
  const {onChangePage, pageResponse, delRecord, handleRecord} = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

  useEffect(() => {
    setSelectedRowKeys([])
  }, [pageResponse]);

  const taskStatusArr = [
    {value: "0", text: "未处理"},
    {value: "1", text: "已处理"},
  ]

  const renderTableOperation = (text: any, record: any) => {
    const funcBtnsProps: FuncGroupsProps = {
      btns: [
        {
          key: `del`,
          text: "删除",
          confirmMsg: "确认删除该警报吗？",
          para: [record.id],
          onClick: delRecord,
          dropdownVisible: false
        },
      ],
      placement: "bottomLeft",
      htmlType: "a",
    };
    if (record.handleStatus === 0) {
      funcBtnsProps.btns.push({
        key: "handle",
        text: "标为已处理",
        para: [record.id],
        onClick: handleRecord,
        dropdownVisible: false
      });
    }
    const funcs = FuncBtnGroup(funcBtnsProps);
    const result: any[] = [];
    const len = funcs.length - 1;
    funcs.forEach((item, index) => {
      result.push(item);
      if (index < len) {
        result.push(<Divider type="vertical" key={"divd" + index}/>);
      }
    });
    return result;
  };

  const columns: ColumnsType<any> = [
    {
      title: "设备名称",
      dataIndex: "deviceName",
      render: (text: string) => {
        return (
          <div>
            <A onClick={() =>
              history.push("/main/info/manage/basic-information")
            }>
              {text ? text : "-"}
            </A>
          </div>
        );
      },
    },
    {
      title: "异常内容",
      dataIndex: "info",
      render: (text: string) => {
        return <div>{text ? text : "-"}</div>;
      },
    },
    {
      title: "警报时间",
      dataIndex: "alarmTime",
      render: (text: string) => {
        return <div>{text ? text : "-"}</div>;
      },
      sorter: (data1: any, data2: any) => {
        let diff = Moment(data1.alarmTime).valueOf() - Moment(data2.alarmTime).valueOf();
        if (diff === 0) {
          if ((data1.id || 0) > (data2.id || 0)) {
            diff = 1;
          } else {
            diff = -1;
          }
        }
        return diff;
      },
    },
    {
      title: "处理状态",
      dataIndex: "handleStatus",
      render: (text: number) => {
        return text === 0 ? "未处理" : "已处理";
      },
      filterMultiple: false,
      filters: taskStatusArr,
      onFilter: (value: string | number | boolean, record: any) => {
        return record.handleStatus + "" === value;
      },
    },
    {
      title: "处理时间",
      dataIndex: "handleTime",
      render: (text: string) => {
        return <div>{text ? text : "-"}</div>;
      },
      sorter: (data1: any, data2: any) => {
        let diff = Moment(data1.handleTime).valueOf() - Moment(data2.handleTime).valueOf();
        if (diff === 0) {
          if ((data1.id || 0) > (data2.id || 0)) {
            diff = 1;
          } else {
            diff = -1;
          }
        }
        return diff;
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      render: (text: any, record: any) => {
        return renderTableOperation(text, record);
      },
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: any) => {
      // setSelectedRowKeys(_.words(keys));
      setSelectedRowKeys(keys);
    }
  }

  const renderBtnsGroup = () => {
    const funcBtnsProps: FuncGroupsProps = {
      btns: [
        {
          key: `del`,
          text: "删除",
          confirmMsg: "确认删除已选中的警报吗？",
          para: selectedRowKeys,
          disabled: !Boolean(selectedRowKeys.length),
          onClick: delRecord,
          dropdownVisible: false
        },
        {
          key: `del`,
          text: "标记为已处理",
          para: selectedRowKeys,
          disabled: !Boolean(selectedRowKeys.length),
          onClick: handleRecord,
          dropdownVisible: false
        },
      ],
      placement: "bottomLeft",
      htmlType: "button",
    };
    return (
      <Space size={10}>
        {FuncBtnGroup(funcBtnsProps)}
        <Button type="dashed">
          <SyncOutlined/>
        </Button>
        {`-共${pageResponse?.pageInfo.total}条记录`}
      </Space>
    );
  };

  return (
    <div className="listContainer">
      <div className="bths">{renderBtnsGroup()}</div>
      <Table
        rowKey="id"
        rowSelection={rowSelection}
        columns={columns}
        dataSource={pageResponse?.data}
        onChange={(pagination, filters, sorter) => {
          console.log(pagination)
          console.log(filters)
          console.log(sorter)
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          current: pageResponse?.pageInfo.page || 0,
          pageSize: pageResponse?.pageInfo.size || 5,
          total: pageResponse?.pageInfo.total || 0,
          pageSizeOptions: ["5", "10", "15", "20"],
          showTotal: (total) => `共 ${total} 条`,
          onChange: (pageNo, pageSize) => {
            console.log(pageNo, pageSize)
            onChangePage({page: pageNo, size: pageSize})
          },
        }}
      />
    </div>
  );
};

export default AlarmList;
